import datetime
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings


class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project=None


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """如果用户已登录，在request中赋值"""
        request.tracer = Tracer()
        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_obj

        # 在中间件中增加判断用户是否登录的逻辑，以便控制用户是否可以访问某些页面
        # 已登录，继续访问页面；未登录，则返回登录页面
        # 通过增加白名单的方式来解决没有登录都可以访问的url
        # 如果是白名单，则用户可以随意访问
        if request.path_info in settings.WHITH_REGEX_URL_LIST:
            return
        # 如果不是白名单，则进行用户登录的判断
        if not request.tracer.user:
            return redirect('web:login')

        # 登录成功之后，访问后台管理时
        # 获取当前用户所拥有的额度(id最大，代表最近的一次交易记录)
        obj = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # 判断是否已过期
        current_datetime = datetime.datetime.now()
        if obj.end_datetime and obj.end_datetime < current_datetime:
            obj = models.Transaction.objects.filter(user=user_obj, status=2, price_policy__category=1).first()

        request.tracer.price_policy = obj.price_policy

    def process_view(self, request, view,args, kwargs):
        # 判断url是否以manage开头
        if not request.path_info.startswith('/manage/'):
            return
        # 判断项目id是否是我创建或参与的
        # 先从中间件中获取id
        project_id = kwargs.get('project_id')
        # 是否是我创建的项目
        project_object=models.Project.objects.filter(creator=request.tracer.user,id=project_id).first()
        if project_object:
            request.tracer.project=project_object
            return
        # 是否是我参与的项目
        projece_user_object=models.ProjectUser.objects.filter(user=request.tracer.user,id=project_id).first()
        if projece_user_object:
            request.tracer.project=projece_user_object.project
            return
        return redirect('web:project_list')